﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using UserControlLib.Actions;

namespace UserControlLib
{
    /// <summary>
    /// RainbowBoundText.xaml 的交互逻辑
    /// </summary>
    public partial class RainbowBoundText : UserControl
    {

        private int _completedCount = 0;
        private int _totalCharacters = 0;
        private bool _isLeftToRight = true; // 控制动画方向

        // 实例属性 Characters
        public ObservableCollection<char> Characters { get; } = new ObservableCollection<char>();

        // 定义 Text 依赖属性
        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register("Text", typeof(string), typeof(RainbowBoundText),
                new PropertyMetadata("彩虹字控件", OnTextChanged));

        // Text 属性
        public string Text
        {
            get => (string)GetValue(TextProperty);
            set => SetValue(TextProperty, value);
        }

        // 定义 IsLeftToRight 依赖属性
        public static readonly DependencyProperty IsLeftToRightProperty =
            DependencyProperty.Register("IsLeftToRight", typeof(bool), typeof(RainbowBoundText),
                new PropertyMetadata(true));

        // IsLeftToRight 属性
        public bool IsLeftToRight
        {
            get => (bool)GetValue(IsLeftToRightProperty);
            set => SetValue(IsLeftToRightProperty, value);
        }

        // Text 属性变化时的回调
        private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as RainbowBoundText;
            if (control != null)
            {
                control.UpdateCharacterCollection();
            }
        }

        public RainbowBoundText()
        {
            InitializeComponent();
            Loaded += RainbowBoundText_Loaded;
        }

        private void RainbowBoundText_Loaded(object sender, RoutedEventArgs e)
        {
            // 确保 CharacterItemsControl 是实例成员
            _totalCharacters = CharacterItemsControl.Items?.Count ?? 0;
        }

        private void OnAnimationCompleted(object sender, EventArgs e)
        {
            // 切换动画方向
            IsLeftToRight = !IsLeftToRight;
            //_completedCount++;

            //// 当所有字符的动画都完成后，重置计数器并重新启动动画
            //if (_completedCount == _totalCharacters)
            //{
            //    ResetAnimations();

            //    // 切换动画方向
            //    _isLeftToRight = !_isLeftToRight;
            //    IsLeftToRight = _isLeftToRight;

            //    StartAnimations();
            //    _completedCount = 0;
            //}

            // 重置所有字符的位置到初始状态（Y = -10）
            ResetAnimations();
        }

        private void ResetAnimations()
        {
            // 重置所有字符的位置到初始状态（Y = -10）
            foreach (var item in CharacterItemsControl.Items)
            {
                var container = CharacterItemsControl.ItemContainerGenerator.ContainerFromItem(item);
                if (container != null)
                {
                    var textBlock = FindVisualChild<TextBlock>(container);
                    if (textBlock != null)
                    {
                        var translateTransform = (TranslateTransform)textBlock.RenderTransform;
                        translateTransform.Y = -10;
                    }
                }
            }
        }

        private void StartAnimations()
        {
            // 重置所有字符的位置到初始状态（Y = -10）
            ResetAnimations();
            // 切换动画方向
            IsLeftToRight = !IsLeftToRight;
        }

        private void OnStoryboardCompleted(object sender, EventArgs e)
        {
            _completedCount++;

            if (_completedCount == _totalCharacters)
            {
                // 切换动画方向
                IsLeftToRight = !IsLeftToRight;

                // 重新启动动画
                StartAnimations();
            }
        }

        private void UpdateCharacterCollection()
        {
            Characters.Clear();

            if (!string.IsNullOrEmpty(Text))
            {
                foreach (var ch in Text)
                {
                    Characters.Add(ch);
                }
            }

            CharacterItemsControl.ItemsSource = Characters;
            CharacterItemsControl.AlternationCount = Characters.Count;

            // 延迟启动动画，确保所有 UI 元素已经完全渲染
            Dispatcher.BeginInvoke(new Action(StartAnimations), System.Windows.Threading.DispatcherPriority.Loaded);
        }

        // 辅助方法：递归查找视觉树中的指定类型子元素
        private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child is T t)
                {
                    return t;
                }

                var result = FindVisualChild<T>(child);
                if (result != null)
                {
                    return result;
                }
            }
            return null;
        }
    }
}
